/* 
 *  Created By: Mike Stevens
 *  Project URL: http://www.codeplex.com/sitesecuritymgmt
 *  License: GNU GPL v2
 *  Copyright (C) 2008 Mike Stevens
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using SiteSecurityManagement;
using SiteSecurityManagement.Service;
using SiteSecurityManagement.Service.SharePoint;



namespace SiteSecurityManagement
{
    public partial class BulkEditSecurity : Page
    {
        #region Members

        private BulkEditSecurityDataService m_userDataTable;

        private const string REDIRECTPAGE = "ssmu_editSecurity.aspx";

        private const string ROLENAMEDESCDELIMITER = " - ";
        #endregion

        #region Constructor/Destructor
        #endregion

        #region Properties
	
        #endregion

        #region Methods
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //Get the string representation of the avaiable SP objects to compare against our selected tree node objects
            
            char pathSeperator=secTree.GetPathSeperator();
            if (secTree.GetSelectedItems().Count == 0)
            {
                generalError.Text = this.GetGlobalResourceObject("ssmu", "noSelectedTreeItems").ToString();
                return;
            }

            foreach (TreeNode node in secTree.GetSelectedItems())
            {
                BulkEditSecurityUtility.SetSecurity(node,m_userDataTable,pathSeperator);
            }
            this.Context.Response.Redirect(SPContext.Current.Web.Url + "/_layouts/" + REDIRECTPAGE);
        }

        protected void spgvwUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                m_userDataTable.DeleteRow(e.RowIndex);
                SaveDataTable();
                spgvwUsers.DataBind();

                if (m_userDataTable.GetRowCount() == 0)
                {
                    btnSubmit.Enabled = false;
                }
            }
            catch { }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder roleNames = new StringBuilder();
                BuildRoleColumnData(roleNames);

                Dictionary<string, string>[] dict = new Dictionary<string, string>[userPicker.Entities.Count];

                for (int i = 0; i < userPicker.Entities.Count; i++)
                {
                    string displayName=((PickerEntity)userPicker.Entities[i]).DisplayText;
                    string userType=BulkEditSecurityUtility.GetFriendlyPrincipal(((PickerEntity)userPicker.Entities[i]).EntityData["PrincipalType"].ToString());
                    string accountName = ((PickerEntity)userPicker.Entities[i]).Description;

                    dict[i] = new Dictionary<string, string>();
                    dict[i].Add(m_userDataTable.UserDisplayNameColumnName,displayName);
                    dict[i].Add(m_userDataTable.UserTypeColumnName,userType);
                    dict[i].Add(m_userDataTable.UserAccountNameColumnName,accountName);
                    dict[i].Add(m_userDataTable.UserPermissionsColumnName,roleNames.ToString());
                }

                m_userDataTable.BuildDataTable(dict);

                spgvwUsers.DataSource = m_userDataTable.GetDataSource;
                spgvwUsers.DataBind();

                btnSubmit.Enabled = true;
            }
            catch
            { }
        }

        private void ClearCheckboxList()
        {
            foreach (ListItem listItem in cblRoles.Items)
            {
                if (true == listItem.Selected)
                {
                    listItem.Selected = false;
                }
            }
        }

        private void BuildRoleColumnData(StringBuilder roleNames)
        {
            foreach (ListItem listItem in cblRoles.Items)
            {
                if (true == listItem.Selected)
                {
                    if (roleNames.Length > 1)
                    {
                        roleNames.Append(", ");
                    }
                    //get role name
                    int indexOfDelimiter = listItem.Text.IndexOf(ROLENAMEDESCDELIMITER);
                    string roleName = listItem.Text.Remove(indexOfDelimiter);
                    roleNames.Append(roleName);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                m_userDataTable = new BulkEditSecurityDataService("UserTable");

                PopulateRoleDefinitons(SPContext.Current.Web);
                SaveDataTable();
            }
            else
            {
                UpdateDataTable();
                spgvwUsers.DataSource = m_userDataTable.GetDataSource;
                spgvwUsers.DataBind();
            }
        }

        protected void SaveDataTable()
        {
            ViewState["userTable"] = m_userDataTable;
        }

        protected void UpdateDataTable()
        {
            m_userDataTable = (BulkEditSecurityDataService)ViewState["userTable"];
        }

        protected void PopulateRoleDefinitons(SPWeb site)
        {
            SPSiteSecurity siteSec = new SPSiteSecurity(site);
            string[] roleDefs = siteSec.GetRoleDefinitions(site);
            foreach (string roleDef in roleDefs)
            {
                if (false == roleDef.Contains("Limited Access"))
                {
                    //break out the role string to its id, name, and description
                    string[] roleDefDetail = roleDef.Split(new char[] { ';' });
                    if (roleDefDetail.Length >= 3)
                    {
                        ListItem listItem = new ListItem(roleDefDetail[1] + ROLENAMEDESCDELIMITER + roleDefDetail[2], roleDefDetail[0]);
                        cblRoles.Items.Add(listItem);
                    }
                }
            }
        }

        #endregion
    }
}